#include "bluezagent.h"
#include <KF5/BluezQt/bluezqt/device.h>
#include <QInputDialog>
#include "pairdialog.h"
struct BluezAgent::BluezAgentPrivate
{
    PairDialog* dialog;
};

BluezAgent::BluezAgent(QObject* parent):
    BluezQt::Agent(parent),
    d_ptr(new BluezAgentPrivate)
{
    d_ptr->dialog = new PairDialog();
}

BluezAgent::~BluezAgent()
{
    delete d_ptr->dialog;
    delete d_ptr;
}

QDBusObjectPath BluezAgent::objectPath()const
{
    return QDBusObjectPath("/org/bluezWidget/agent");
}

BluezQt::Agent::Capability BluezAgent::capability()const
{
    return DisplayYesNo;
}

void BluezAgent::requestPinCode(BluezQt::DevicePtr device, const BluezQt::Request<QString>& request)
{
    bool ok;
    QString pin = QInputDialog::getText(nullptr,
                                        tr("PIN Required"),
                                        tr("Enter PIN for %1:").arg(device->name()),
                                        QLineEdit::Normal,
                                        QString(),
                                        &ok);

    if (ok && !pin.isEmpty())
    {
        request.accept(pin);
    }
    else
    {
        request.cancel();
    }

}

void BluezAgent::displayPinCode(BluezQt::DevicePtr device, const QString& pinCode)
{
    int result = d_ptr->dialog->showConfirmation(0x00, device->name(), pinCode);
    if(result == QDialog::Rejected)
    {
        device->cancelPairing();
    }
}

void BluezAgent::requestPasskey(BluezQt::DevicePtr device, const BluezQt::Request<quint32>& request)
{
    Q_UNUSED(device);
    Q_UNUSED(request);
}

void BluezAgent::displayPasskey(BluezQt::DevicePtr device, const QString& passkey, const QString& entered)
{
    Q_UNUSED(entered);
    d_ptr->dialog->showConfirmation(0x01, device->name(), passkey);
}

void BluezAgent::requestAuthorization(BluezQt::DevicePtr device, const BluezQt::Request<>& request)
{
    Q_UNUSED(device);
    //这里是显示对话界面，在根据返回数决定是否接受request
//        int result = d_ptr->dialog->showConfirmation(0x04, device->name());
//        if (result == QDialog::Accepted)
//        {
//            request.accept();
//        }
//        else
//        {
//            request.reject();
//        }
    request.accept();
}

void BluezAgent::requestConfirmation(BluezQt::DevicePtr device, const QString& passkey, const BluezQt::Request<>& request)
{
    int result = d_ptr->dialog->showConfirmation(0x02, device->name(), passkey);
    if (result == QDialog::Accepted)
    {
        // qDebug("device connected?:%d",device->isConnected());
        emit acceptDevice(device->address(), device->isConnected());
        request.accept();
    }
    else
    {
        request.reject();
    }
}

void BluezAgent::authorizeService(BluezQt::DevicePtr device, const QString& uuid, const BluezQt::Request<>& request)
{
    Q_UNUSED(device);
    Q_UNUSED(uuid);
    request.accept();
}

void BluezAgent::cancel()
{

}

void BluezAgent::release()
{

}

